<template>
  <div class="app-container">

    <el-card class="box-card">
      <el-form :rules="rules" ref="ruleForm" :model="ruleForm" label-width="150px" v-loading='loading'>

        <el-form-item label="缩略图" prop="shrinkImgoss">
          <el-upload :data='{dirName:""}' :headers="headers" :limit="1" list-type="picture-card" ref="uploadIMG" :on-remove="handleRemoveImg" :action="uploadPath" :auto-upload="false" :on-success="handleAvatarSuccess" :on-error="handleErrorImg" :on-change="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="网站压缩" prop="weboss">
          <el-upload :data='{dirName:""}' :headers="headers" ref="uploadZIP" class="avatar-uploader" :on-remove="handleRemoveZIP" :limit="1" :file-list="fileList" :action="uploadPath" :auto-upload="false" :on-error="handleErrorZip" :on-success="handleAvatarSuccessWEB" :on-change="beforeAvatarUploadWEB">
            <i class="el-icon-plus">添加网站压缩包</i>
          </el-upload>
        </el-form-item>

        <el-form-item label="版本类型：" prop="versionType">
          <el-select @change="bindversionType" v-model="ruleForm.versionType" placeholder="请选择">
            <el-option v-for="item in versionTypeID" :key="item.id" :label="item.displayName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="引擎类型：" prop="engineType">
          <el-select @change="bindengineType" v-model="ruleForm.engineType" placeholder="请选择">
            <el-option v-for="item in engineTypeID" :key="item.id" :label="item.displayName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购买类型：" prop="purchaseType">
          <el-select @change="bindpurchaseType" v-model="ruleForm.purchaseType" placeholder="请选择">
            <el-option v-for="item in purchaseTypeID" :key="item.id" :label="item.displayName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="版本名称：" prop="versionName">
          <el-input v-model="ruleForm.versionName" />
        </el-form-item>
        <el-form-item label="文件地址：" prop="aliOss">
          <el-input v-model="ruleForm.aliOss" />
        </el-form-item>

        <el-form-item label="版本详细介绍" prop="detail">
          <div style="border: 1px solid #ccc; margin-top: 10px;">
            <!-- 工具栏 -->
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
            <!-- 编辑器 -->
            <Editor style="height: 400px; overflow-y: hidden;" :defaultConfig="editorConfig" v-model="ruleForm.detail" @onChange="onChange" @onCreated="onCreated" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button :loading='loading' type="primary" @click="handlePublish">保存</el-button>
        </el-form-item>

      </el-form>
    </el-card>

  </div>
</template>



<script>
import { create, displaytypeList } from '@/api/version/goods'
import { createStorage, uploadPath } from '@/api/storage'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getToken } from '@/utils/auth'
import '@wangeditor/editor/dist/css/style.css'

export default {
  name: 'GoodsCreate',
  components: { Editor, Toolbar },

  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          uploadImage: {
            server: uploadPath,
            fieldName: 'file',
            onSuccess: () => {},
            meta: {
              dirName: ''
            },
            onError: (file, err, res) => {
              this.$message.error(`${file.name} 上传出错`)
            }
          }
        }
      },
      fileList: [],
      loading: false,
      uploadPath: uploadPath,
      purchaseTypeID: '', // 购买类型
      engineTypeID: '', // 引擎类型
      versionTypeID: '', // 版本类型
      ruleForm: {
        purchaseType: '',
        engineType: '',
        versionType: '',
        versionName: '', // 版本名称
        detail: '',
        aliOss: '',
        weboss: '',
        shrinkImgoss: '', // 缩略图地址
        shrinkImg: '', // 缩略图地址
        openAreaWebsite: '' // 开区网站
      },
      rules: {
        versionName: [
          { required: true, message: '请输入版本名称', trigger: 'blur' }
        ],
        shrinkImgoss: [
          {
            required: true,
            message: '请填上传正确格式的缩略图',
            trigger: 'change'
          }
        ],
        weboss: [
          {
            required: true,
            message: '请填上传正确格式的网站压缩包',
            trigger: 'change'
          }
        ],
        detail: [{ required: true, message: '请填写详情', trigger: 'blur' }],
        aliOss: [
          { required: true, message: '请填写文件地址', trigger: 'blur' }
        ],
        versionType: [
          { required: true, message: '请选择版本类型', trigger: 'change' }
        ],
        engineType: [
          { required: true, message: '请选择引擎类型', trigger: 'change' }
        ],
        purchaseType: [
          { required: true, message: '请选择购买类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Hyxxkj-Admin-Token': getToken()
      }
    }
  },
  created() {},
  mounted() {
    displaytypeList({ type: 2 }).then((res) => {
      this.purchaseTypeID = res.data.data.list
    })
    displaytypeList({ type: 1 }).then((res) => {
      this.engineTypeID = res.data.data.list
    })
    displaytypeList({ type: 0 }).then((res) => {
      this.versionTypeID = res.data.data.list
    })
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    },
    onChange(editor) {
      //  console.log('onChange', editor.getHtml()) // onChange 时获取编辑器最新内容
    },
    handleErrorImg() {
      this.$message.error('图片上传出错')
    },
    handleRemoveImg() {
      this.ruleForm.shrinkImgoss = ''
      this.ruleForm.shrinkImg = ''
    },
    handleAvatarSuccess(res, file) {
      if (res.errno == 0) {
        this.ruleForm.shrinkImg = res.data.url
        this.$refs.uploadZIP.submit()
      }
    },
    beforeAvatarUpload(file) {
      console.log(file)
      var isJPG = false
      if (
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/png' ||
        file.raw.type === 'image/gif'
      ) {
        isJPG = true
      }
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return
      }
      this.ruleForm.shrinkImgoss = URL.createObjectURL(file.raw)
      return isJPG && isLt2M
    },

    handleErrorZip() {
      this.$message.error('压缩包上传出错')
    },
    handleRemoveZIP() {
      this.ruleForm.openAreaWebsite = ''
      this.ruleForm.weboss = ''
    },
    handleAvatarSuccessWEB(res, file) {
      if (res.errno == 0) {
        this.ruleForm.openAreaWebsite = res.data.url
        console.log(this.ruleForm)
        this.versionCreate(this.ruleForm)
      }
    },
    beforeAvatarUploadWEB(file) {
      const isJPG = file.raw.type === 'application/x-zip-compressed'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!isJPG) {
        this.$message.error('上传压缩包只能是zip格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传压缩包大小不能超过 200MB!')
        return
      }
      this.ruleForm.weboss = file.name
      return isJPG && isLt2M
    },

    bindversionType() {},
    bindengineType() {},
    bindpurchaseType() {},
    handleCancel: function() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/goods/list' })
    },
    handlePublish() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$refs.uploadIMG.submit()
        } else {
          this.$message({
            message: '请检查数据必填项',
            type: 'warning'
          })
          return false
        }
      })
    },

    versionCreate(e) {
      this.loading = true
      create(e)
        .then((res) => {
          if (res.data.errno == 0) {
            this.loading = false
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.$router.push({ path: '/goods/list' })
          }
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #dcdc;
}
.avatar {
  width: 178px;
  height: 178px;
}
</style>